﻿using HtmlAgilityPack;
using Microsoft.Extensions.Logging;
using Microsoft.Playwright;
using Newtonsoft.Json;
using Org.BouncyCastle.Ocsp;
using Rw.Core.Common;
using Rw.Core.Common.Paging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using WH.Common.Config;
using WH.Common.UniOfWork;
using WH.Contracts.RemoveWatermark;
using WH.Model.RemoveWatermark;
using WH.Repositories.IRepositories.RemoveWatermark;
using WH.Services.BaseService;
using WH.Services.IServices.IRemoveWatermark;
using static System.Net.WebRequestMethods;

namespace WH.Services.Services.RemoveWatermark
{
    public class RemoveWatermarkService : BaseService<RemoveWatermarkEntity>, IRemoveWatermarkService
    {
        private readonly ILogger<RemoveWatermarkService> _log;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IConfigurationCenter _configuration;
        private readonly IRemoveWatermarkRepository _removeWatermarkRepository;
        
        public RemoveWatermarkService(
            ILogger<RemoveWatermarkService> log,
            IUnitOfWork unitOfWork,
            IConfigurationCenter configuration,
            IRemoveWatermarkRepository removeWatermarkRepository) : base(removeWatermarkRepository)
        {
            _log = log;
            _unitOfWork = unitOfWork;
            _configuration = configuration;
            _removeWatermarkRepository = removeWatermarkRepository;
        }
        /// <summary>
        /// 保存信息
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public async Task<string> RemoveWatermarkSaveAsync(RemoveWatermarkInputDto parm)
        {
            try
            {
                var afterUrl = await GetHtmlByUrl(parm.PreUrl);
                if (string.IsNullOrEmpty(parm.Id))
                {
                    parm.Id = Snowflake.GetNewId();
                }
                //=============添加文件============
                RemoveWatermarkEntity removeWatermark = new RemoveWatermarkEntity()
                {
                    Id = parm.Id,
                    Code = parm.Code,
                    OpenId = parm.OpenId,
                    PreUrl = parm.PreUrl,
                    AfterUrl = afterUrl,
                    Remark = parm.Remark,
                    OrganizationId="0",
                };
                await _removeWatermarkRepository.SaveAsync(removeWatermark);
                //=========================
                await _unitOfWork.CommitTranAsync();
                return afterUrl;
            }
            catch (Exception ex)
            {
                var msg = JsonConvert.SerializeObject(parm);
                _log.LogError("RemoveWatermarkSaveParmAsync:" + msg);
                _log.LogError("RemoveWatermarkSaveMessageAsync:" +  ex.Message);
                await _unitOfWork.RollbackTranAsync();
                throw;
            }
        }
        private async Task<string> GetHtmlByUrl(string htmlurl)
        {
            if (htmlurl.Contains("http"))
            {
                htmlurl = htmlurl.Substring(htmlurl.IndexOf("http"));
            }
            var options = new BrowserTypeLaunchOptions() { };
            options.Headless = false;
            options.ChromiumSandbox = true;
            options.ExecutablePath = _configuration.VideoOptions?.ExecutablePath;
            var playwright = await Playwright.CreateAsync();
            var browser = await playwright.Chromium.LaunchAsync(options);
            var page = await browser.NewPageAsync();
            try
            {
                await page.GotoAsync(htmlurl);
                if (htmlurl.ToLower().Contains("douyin"))
                {
                    var loctor = page.Locator(".douyin-login__close.dy-account-close"); // 根据实际情况修改选择器
                                                                                        // 异步点击按钮
                    await loctor.ClickAsync();
                }
                // 假设点击某个按钮会打开登录窗口
                var content = await page.ContentAsync();
                _log.LogError("RemoveWatermarkSaveParmAsync:" + content);
                //Console.WriteLine(content);

                //var video = await page.QuerySelectorAllAsync("video");
                //foreach (var button in video)
                //{
                //    Console.WriteLine(await button.InnerTextAsync());
                //}
                //var videoSource = await page.EvaluateAsync<string>(@"() => {
                //    const video = document.querySelector('video'); // 选择video标签
                //    if (video && video.getElementsByTagName('source')[0]) {
                //        return video.getElementsByTagName('source')[0].src; // 获取source属性
                //    }
                //    return null;}");
                var videoSource = "";
                if (htmlurl.ToLower().Contains("douyin"))
                {
                    videoSource = await page.EvaluateAsync<string>(@"() => {
                const video = document.querySelectorAll('video'); // 选择video标签
                if (video){
                    for(var i=0;i<video.length;i++){
                        if (video[i].getElementsByTagName('source')[0] && video[i].getElementsByTagName('source')[0].src.indexOf('v3-web')!=-1) {
                            return video[i].getElementsByTagName('source')[0].src; // 获取source属性
                        }
                        if (video[i].getElementsByTagName('source')[1]  &&  video[i].getElementsByTagName('source')[1].src.indexOf('v3-web')!=-1) {
                            return video[i].getElementsByTagName('source')[1].src; // 获取source属性
                        }
                        if (video[i].getElementsByTagName('source')[2]  && video[i].getElementsByTagName('source')[2].src.indexOf('v3-web')!=-1) {
                            return video[i].getElementsByTagName('source')[2].src; // 获取source属性
                        }
                    }
                }
                return null;}");
                }
                else
                {
                    videoSource = await page.EvaluateAsync<string>(@"() => {
                const video = document.querySelectorAll('video'); // 选择video标签
                if (video){
                    for(var i=0;i<video.length;i++){
                        if (video[i].getElementsByTagName('source')[0]) {
                            return video[i].getElementsByTagName('source')[0].src; // 获取source属性
                        }
                    }
                }
                return null;}");
                }
                await browser.CloseAsync();
                return videoSource;
            }
            catch (Exception ex)
            {
                _log.LogError("GetHtmlByUrl:" + ex.Message);
                await browser.CloseAsync();
                throw;
            }
        }
        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="proId"></param>
        /// <returns></returns>
        public async Task<bool> RemoveWatermarkDeleteAsync(string[] ids)
        {
            try
            {
                await _unitOfWork.BeginTranAsync();
                await _removeWatermarkRepository.RemoveAsync(x => ids.Contains(x.Id));
                await _unitOfWork.CommitTranAsync();
            }
            catch (Exception)
            {
                await _unitOfWork.RollbackTranAsync();
                throw;
            }
            return true;
        }
        /// <summary>
        /// 分页检索
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public async Task<IPagedList<RemoveWatermarkOutputDto>> GetRemoveWatermarkPageListAsync(RemoveWatermarkFilterDto parm)
        {
            //=========================end=====================
            var list = await _removeWatermarkRepository.GetRemoveWatermarkByPageAsync(parm);
            return list;
        }
        /// <summary>
        /// 数据导出
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public async Task<IEnumerable<RemoveWatermarkExportDto>> DataExportAsync(RemoveWatermarkFilterDto model)
        {
            var data = await _removeWatermarkRepository.DataExportAsync(model);
            return data;
        }
    }
}
